﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lk.WebTow.Authorize;
using Lk.WebTow.Common;
using Lk.WebTow.Common.Config;
using Lk.WebTow.Data;
using Lk.WebTow.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Lk.WebTow.Areas.Admin.Controllers
{

    [Area("Admin")]
    [AdminAuthorize]
    public class BaseController : Controller
    {

        public BaseController()
        {


        }
        public SiteConfig siteConfig = new SiteConfig();
        public NcManager siteAdminInfo = new NcManager();
        public ApplicationDbContext dbContext;
        private readonly ConfigSite configSite = new ConfigSite();
        public BaseController(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            var session = HttpContext.Session.Get(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme);
            if (session == null)
            {
                return false;
            }
            siteAdminInfo = ByteConvertHelper.Bytes2Object<NcManager>(session);
            if (siteAdminInfo != null)
            {
                return true;
            }
            else
            {
                var cookieAdmin = HttpContext.AuthenticateAsync(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme);
                cookieAdmin.Wait();

                var adminName = cookieAdmin.Result.Principal.Claims.FirstOrDefault(s => s.Type == "AdminName")?.Value;
                var adminPwd = cookieAdmin.Result.Principal.Claims.FirstOrDefault(s => s.Type == "AdminPwd")?.Value;

                if (!string.IsNullOrWhiteSpace(adminName) && !string.IsNullOrWhiteSpace(adminPwd))
                {
                    var manager = dbContext.NcManager.FirstOrDefault(s => s.UserName == adminName && s.Password == adminPwd);
                    HttpContext.Session.Set(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme, ByteConvertHelper.Object2Bytes(manager));
                    siteAdminInfo = ByteConvertHelper.Bytes2Object<NcManager>(session);
                    return true;
                }
            }
            return false;
        }
    }
}
